package com.qfedu.fmmall.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.qfedu.fmmal.vo.ResStatus;
import com.qfedu.fmmal.vo.ResultVO;
import com.qfedu.fmmall.config.MyPayConfig;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/order")
@Api(value = "提供订单相关的操作接口",tags = "订单管理")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/add")
    public ResultVO add(String cids,@RequestBody Orders order) {
        ResultVO resultVO = null;
        try {
            Map<String,String> orderInfo = orderService.addOrder(cids,order);
            String orderId = orderInfo.get("orderId");
            //String orderId="1234561234567";
            if (order != null){
                //微信支付：申请支付连接
                WXPay wxPay = new WXPay(new MyPayConfig());

                HashMap<String,String> data = new HashMap<>();
                data.put("body",orderInfo.get("productNames"));//商品描述
                data.put("out_trade_no",orderId);//使用当前用户订单的编号作为当前用户订单的编号作为当前交易的交易号
                data.put("fee_type","CNY");//支付币种
                data.put("total_fee",order.getActualAmount()*100+"");//支付总金额(单位：分）
                data.put("trade_type","NATIVE");//交易类型
                data.put("notify_url","http://ly01.free.idcfengye.com/pay/callback");//订单编号
                //发送请求获取响应
                Map<String, String> resp = wxPay.unifiedOrder(data);

               System.out.println(resp);
                orderInfo.put("payUrl",resp.get("code_url"));
                resultVO = new ResultVO(ResStatus.OK,"提交订单成功！",orderInfo);
            }else {
                resultVO = new ResultVO(ResStatus.NO,"提交订单失败",null);
            }

        }catch (SQLException e){
            resultVO = new ResultVO(ResStatus.NO,"提交订单失败",null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultVO;
    }


    @GetMapping("/status/{oid}")
    public ResultVO getOrderStatus(@PathVariable("oid") String orderId,@RequestHeader("token")String token){
        ResultVO resultVO = orderService.GetOrderById(orderId);
        return resultVO;

    }
}
